using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using mshtml;
using OFX.Aggregator.WebScraping.Infrastructure;

namespace OFX.Aggregator.WebScraping.Implementation
{
	internal class HtmlDocumentWrapper : IHtmlDocument, IDisposable
	{
		private readonly HtmlDocumentManager documentManager;
		private readonly HtmlDocument htmlDocument;
		private readonly HTMLDocumentClass htmlDomDocument;

		[DebuggerStepThrough]
		public HtmlDocumentWrapper(HTMLDocumentClass htmlDomDocument)
		{
			this.documentManager = new HtmlDocumentManager();

			this.htmlDomDocument = htmlDomDocument;
		}

		[DebuggerStepThrough]
		public HtmlDocumentWrapper(HtmlDocument htmlDocument)
		{
			this.documentManager = new HtmlDocumentManager();

			this.htmlDocument = htmlDocument;
			this.htmlDomDocument = (HTMLDocumentClass) htmlDocument.DomDocument;
		}

		#region Implementation of IDisposable

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		/// <filterpriority>2</filterpriority>
		public void Dispose()
		{
			this.documentManager.Dispose();
		}

		#endregion

		#region Implementation of IHtmlDocument

		[DebuggerStepThrough]
		public IHtmlElement GetElementById(string id)
		{
			return this.documentManager.GetWrapper(this.htmlDomDocument.getElementById(id));
		}

		[DebuggerStepThrough]
		public void InvokeScript(string scriptName, object[] args)
		{
			if (this.htmlDocument == null)
				throw new InvalidOperationException();

			this.htmlDocument.InvokeScript(scriptName, args);
		}

		public IList<IHtmlFrameWindow> Frames
		{
			[DebuggerStepThrough]
			get { return new HtmlFrameWindowList(this.htmlDomDocument.frames, this.documentManager); }
		}

		public IHtmlElementCollection All
		{
			[DebuggerStepThrough]
			get { return this.documentManager.GetWrapper(this.htmlDomDocument.all); }
		}

		#endregion
	}
}